package cn.td0f7.android.wangzhongcourse;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

public class ThreadActivity extends AppCompatActivity {
    private Button btn;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thread);
        btn = findViewById(R.id.btn);

        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        btn.setText("子线程 case 1");
                        break;
                    case 2:
                        btn.setText(String.valueOf(msg.obj));
                        break;
                }
            }
        };

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
//                        handler.sendEmptyMessage(1); //发送waht为1的消息
//                        handler.sendEmptyMessageDelayed(1, 500); //延迟0.5秒 发送waht为1的消息

                        Message msg = new Message();
                        msg.what = 2;
                        msg.obj = "case 2 子线程传值";
//                        handler.sendMessage(msg);
                        handler.sendMessageDelayed(msg, 500);
                    }
                }.start();
            }
        });
    }
}